﻿#include "msg_queue.h"
#include "osa.h"

mqd_t create_msg_queue(char* file, int block, int len, int size)
{
	mqd_t msg_id = (mqd_t)-1;
	struct mq_attr mqattr = { 0 };

	mqattr.mq_maxmsg = len;
	mqattr.mq_msgsize = size;

	msg_id = mq_open(file, O_RDWR | O_CREAT | O_EXCL | (block ? 0 : O_NONBLOCK), 0666, &mqattr);
	if (msg_id < (mqd_t)0)
	{
		mq_unlink(file);
		msg_id = mq_open(file, O_RDWR | O_CREAT | (block ? 0 : O_NONBLOCK), 0666, &mqattr);
	}

	return msg_id;
}

mqd_t get_msg_queue(char* file)
{
	mqd_t msg_id = mq_open(file, O_RDWR);
	if (msg_id == (mqd_t)-1)
	{
		return (mqd_t)-1;
	}

	return msg_id;
}

int destory_msg_queue(mqd_t msg_id, char *file)
{
	if (mq_close(msg_id)<0)
		return -1;
	if (mq_unlink(file)<0)
		return -1;

	return 0;
}

int close_msg_queue(mqd_t msg_id)
{
	if (mq_close(msg_id)<0)
		return -1;

	return 0;
}

int send_msg_queue(mqd_t msg_id, char* msg, int size, int prio)
{
	if (mq_send(msg_id, msg, size, prio) < 0)
		return -1;

	return 0;
}

int recv_msg_queue(mqd_t msg_id, char* out, int size)
{
	unsigned int sender = 0;

	if (mq_receive(msg_id, out, size, &sender) < 0)
		return -1;

	return 0;
}

int msg_count(mqd_t msg_id)
{
	struct mq_attr mqattr = { 0 };

	int ret = mq_getattr(msg_id, &mqattr);
	if (ret < 0)
		return -1;
	else
		return mqattr.mq_curmsgs;
}

int msgq_is_empty(mqd_t msg_id)
{
	if (msg_count(msg_id) > 0)
		return 0;
	else
		return 1;
}

void msgq_get_last(mqd_t msg_id, char* out, int size)
{
	while (msg_count(msg_id) > 0)
	{
		recv_msg_queue(msg_id, out, size);
	}
}


